package com.lse_api.control;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lse_api.config.multipledatasources.DataSourceContextHolder;
import com.lse_api.config.multipledatasources.aspect.DataSource;
import com.lse_api.entity.*;
import com.lse_api.exception.LseException;
import com.lse_api.service.*;
import com.lse_api.utils.DateUtil;
import com.lse_api.utils.FileUploadBoot;
import com.lse_api.utils.ReturnMsg;
import com.lse_api.utils.Status;
import com.lse_api.utils.encryption.AESEncryption;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 用户个性化信息 前端控制器
 * </p>
 *
 * @author 祁雪
 * @since 2020-01-25
 */
@Controller
@RequestMapping("/lseapi/api/userInfo")
public class UserInfoController extends LseException implements ReturnMsg {

    @Resource
    private HttpServletRequest request;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UsersService usersService;

    @Autowired
    private GroupListService groupListService;

    @Autowired
    private GroupUserService groupUserService;

    @Autowired
    private ProjectApiService projectApiService;

    @Autowired
    private ProjectService projectService;

    @Value("${com.lse.fileFolder.userInfo}")
    public String userInfoPath;

    @Value("${com.lse.fileFolder.userInfoFolder}")
    public String userInfoFolder;

    @Value("${com.lse.fileSize}")
    public int fileSize;

    /**
     * 更新用户信息 and 上传头像
     *
     * @param file
     * @param userInfo
     * @return
     */
    @RequestMapping(value = "/updateUserInfo")
    @ResponseBody
    public Status updateUserInfo(MultipartFile file, UserInfo userInfo) {

        if (StringUtils.isEmpty(userInfo.getUid())) {
            return Status.error(UID);
        }

        if (file != null && file.getSize() > fileSize) {
            return Status.error(FILE_MAX);
        }

        Token token = (Token) request.getAttribute("token");

        String fileName = token.getUsersUid() + "_head";

        boolean flag = FileUploadBoot.uploadDefault(file, fileName, userInfoPath);
        if (flag) {

            // 压缩图片
            String suffix = FileUploadBoot.getFileSuffix(file.getOriginalFilename());
            File fileOld = new File(userInfoPath, fileName + suffix);
            try {
                Thumbnails.of(fileOld).scale(1d).outputQuality(0.7d).toFile(fileOld);
            } catch (Exception e) {
                e.printStackTrace();
            }

            String src = "http://" + request.getServerName() + ":" + request.getServerPort() + "/" +
                    request.getContextPath() + "/" + userInfoFolder + "/" + fileName + FileUploadBoot.getFileSuffix(file.getOriginalFilename());
            userInfo.setPortraitUrl(src);
        } else {
            userInfo.setPortraitUrl(null);
        }

        userInfo.setUsersUid(token.getUsersUid());

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("uid", userInfo.getUid());
        userInfoQueryWrapper.eq("users_uid", userInfo.getUsersUid());

        boolean flagx = userInfoService.update(userInfo, userInfoQueryWrapper);

        return flagx ? Status.success(UPDATESUCCESS) : Status.error(UPDATEFAILURE);
    }

    /**
     * 个性化设置 - 上传背景图片
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/updateUserInfoPer")
    @ResponseBody
    public Status updateUserInfoPer(MultipartFile file) {

        String uid = request.getParameter("uid");

        if (StringUtils.isEmpty(uid)) {
            return Status.error(UID);
        }

        Token token = (Token) request.getAttribute("token");

        String fileName = token.getUsersUid() + "_background";

        if (file != null && file.getSize() > fileSize) {
            return Status.error(FILE_MAX);
        }

        boolean flag = FileUploadBoot.uploadDefault(file, fileName, userInfoPath);

        if (flag) {

            // 压缩图片
            String suffix = FileUploadBoot.getFileSuffix(file.getOriginalFilename());
            File fileOld = new File(userInfoPath, fileName + suffix);
            try {
                Thumbnails.of(fileOld).scale(1d).outputQuality(0.7d).toFile(fileOld);
            } catch (Exception e) {
                e.printStackTrace();
            }

            UserInfo userInfo = new UserInfo();
            userInfo.setUid(uid);
            userInfo.setUsersUid(token.getUsersUid());

            String src = "http://" + request.getServerName() + ":" + request.getServerPort() + "/" +
                    request.getContextPath() + "/" + userInfoFolder + "/" + fileName + FileUploadBoot.getFileSuffix(file.getOriginalFilename());
            userInfo.setBackgroundImage(src);

            QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
            userInfoQueryWrapper.eq("uid", userInfo.getUid());
            userInfoQueryWrapper.eq("users_uid", userInfo.getUsersUid());

            boolean flagx = userInfoService.update(userInfo, userInfoQueryWrapper);

            return flagx ? Status.success(UPDATESUCCESS) : Status.error(UPDATEFAILURE);

        } else {
            return Status.error(FILE_IS_NULL);
        }

    }

    /**
     * 读取已登录用户的个人信息
     *
     * @return
     */
    @RequestMapping(value = "/getLoginUserInfo")
    @ResponseBody
    public Status getLoginUserInfo() {

        Token token = (Token) request.getAttribute("token");

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("users_uid", token.getUsersUid());

        UserInfo userInfo = userInfoService.getOne(queryWrapper);

        return Status.success(userInfo);
    }

    /**
     * 修改密码
     *
     * @return
     */
    @RequestMapping(value = "/updatePass")
    @ResponseBody
    @DataSource("dataSource_lse")
    public Status updatePass() {
        DataSourceContextHolder.setDB("dataSource_lse");

        Token token = (Token) request.getAttribute("token");

        String oldPass = request.getParameter("old");
        String newPass = request.getParameter("new");

        if (StringUtils.isEmpty(oldPass)) {
            return Status.error(USER_PASS_EDIT_OLD);
        }

        if (StringUtils.isEmpty(newPass)) {
            return Status.error(USER_PASS_EDIT_NEW);
        }

        // 查询用户账号信息
        Users users = usersService.getById(token.getUsersUid());

        oldPass = AESEncryption.Ecodes(oldPass, users.getAccount());
        newPass = AESEncryption.Ecodes(newPass, users.getAccount());

        if (!oldPass.equals(users.getPass())) {
            return Status.error(USER_PASS_EDIT_OLD_NOT);
        }

        if (newPass.equals(users.getPass())) {
            return Status.error(USER_PASS_EDIT_ON);
        }

        users.setPass(newPass);

        boolean flag = usersService.updateById(users);

        return flag ? Status.success(UPDATESUCCESS) : Status.error(UPDATEFAILURE);
    }

    /**
     * 读取用户统计信息
     * 1. ?个项目
     * 2. ?个API
     * 3. 创建?个项目组
     * 4. 加入?个项目组
     * 5. 热力图 - 今年创建API,项目组,项目的次数 格式[['时间',数字]]
     *
     * @return
     */
    @RequestMapping(value = "/getUserStatistical")
    @ResponseBody
    public Status getUserStatistical() {

        Token token = (Token) request.getAttribute("token");

        Map<String, Object> queryMap = new HashMap<>();

        // 读取已创建的项目
        queryMap.put("project_create", token.getUsersUid());
        Collection<Project> projects = projectService.listByMap(queryMap);

        // 读取已创建的API
        queryMap.clear();
        queryMap.put("api_create", token.getUsersUid());
        Collection<ProjectApi> projectApis = projectApiService.listByMap(queryMap);

        // 读取已创建的项目组
        queryMap.clear();
        queryMap.put("group_create", token.getUsersUid());

        Collection<GroupList> groups = groupListService.listByMap(queryMap);

        // 读取已加入的项目组数量
        QueryWrapper<GroupUser> groupUserQueryWrapper = new QueryWrapper<>();
        groupUserQueryWrapper.eq("user_id", token.getUsersUid())
                .eq("is_create", 0);
        int joinNum = groupUserService.count(groupUserQueryWrapper);

        // 统计热力图数据 (按照 yyyy-MM-dd 时间统计数量)
        Map<String, Integer> map = new HashMap<>();

        // 统计 项目 当前年份
        projects.stream()
                .filter(value -> DateUtil.getOneDateTime(value.getCreateTime(), "yyyy").equalsIgnoreCase(String.valueOf(LocalDate.now().getYear())))
                .forEach(project -> {
                    String time = DateUtil.getOneDateTime(project.getCreateTime(), "yyyy-MM-dd");
                    if (map.get(time) == null) {
                        map.put(time, 1);
                    } else {
                        map.put(time, map.get(time) + 1);
                    }
                });
        // 统计 api 当前年份
        projectApis.stream()
                .filter(value -> DateUtil.getOneDateTime(value.getCreateTime(), "yyyy").equalsIgnoreCase(String.valueOf(LocalDate.now().getYear())))
                .forEach(projectApi -> {
                    String time = DateUtil.getOneDateTime(projectApi.getCreateTime(), "yyyy-MM-dd");
                    if (map.get(time) == null) {
                        map.put(time, 1);
                    } else {
                        map.put(time, map.get(time) + 1);
                    }
                });
        // 统计 已创建的项目组 当前年份
        groups.stream()
                .filter(value -> DateUtil.getOneDateTime(value.getCreateTime(), "yyyy").equalsIgnoreCase(String.valueOf(LocalDate.now().getYear())))
                .forEach(group -> {
                    String time = DateUtil.getOneDateTime(group.getCreateTime(), "yyyy-MM-dd");
                    if (map.get(time) == null) {
                        map.put(time, 1);
                    } else {
                        map.put(time, map.get(time) + 1);
                    }
                });

        // 生成 热力图Data
        List<String[]> hotList = new ArrayList<>();
        map.forEach((k, v) -> {
            hotList.add(new String[]{k, v.toString()});
        });

        Map<String, Object> data = new HashMap<>();
        data.put("project", projects.size());
        data.put("api", projectApis.size());
        data.put("groupMe", groups.size());
        data.put("groupJoin", joinNum);
        data.put("statistical", hotList);
        data.put("year", LocalDate.now().getYear());

        return Status.success(data);
    }

    public static void main(String[] args) {
        /*// 压缩图片
        File fileOld = new File("C:\\Users\\76167\\Desktop\\文档数据\\test\\貂蝉-蝴蝶梦.jpg");
        try {
            Thumbnails.of(fileOld).scale(1d).outputQuality(0.7d).toFile(fileOld);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        System.out.println(LocalDate.now().getYear());
    }

}

